<div class="layui-card">
    <div class="layui-breadcrumb" lay-filter="breadcrumb" style="padding: 0 15px;line-height: 50px;">
        <a lay-href="">概览</a>
        <a><cite>报表中心</cite></a>
        <a><cite lay-href="report/custom">自定义报表</cite></a>
        <a><cite>报表查看</cite></a>
    </div>
    <div class="luomi-title" style="margin-top: 10px;margin-left: -60px; display: flex;justify-content: center;"></div>
</div>

<div style="display: flex;justify-content: center;margin-bottom: 20px;">
    <form class="layui-form" action="" lay-filter="custom-check" style="display: flex;">
        <div class="layui-input-inline" style="margin-right: 10px;">
            <select name="date" lay-verify="required" lay-filter="dateSelect" > 
                <option value="year">年</option>
                <option value="month">月</option>
                <option value="day">日</option>
                </select>
         </div>
         <div class="layui-input-inline " style="display: flex;margin-right: 20px;">
            <input type="text" name="year" lay-filter="year" placeholder="yyyy" autocomplete="off" class="layui-input" id="year" style="width: 67%;" >
            <input type="text" name="month" lay-filter="month" placeholder="yyyy-MM" autocomplete="off" class="layui-input hide" id="month" style="margin-right: 10px;">
            <input type="text" name="month2" lay-filter="month2" placeholder="yyyy-MM" autocomplete="off" class="layui-input hide" id="month2">    
            <input type="text" name="day" lay-filter="day" placeholder="yyyy-MM-DD" autocomplete="off" class="layui-input hide" id="day" style="margin-right: 10px;">
            <input type="text" name="day2" lay-filter="day" placeholder="yyyy-MM-DD" autocomplete="off" class="layui-input hide" id="day2">
         </div>
         <div class="layui-input-inline" style="margin-right: 20px;">
             <button type="button" class="layui-btn" lay-submit lay-filter="custom-check-btn">按时段生成</button>
         </div>
    </form>
    <button class="layui-btn" onclick="save()">下载表格</button>
</div>

<!-- <div style="margin-top:30px;" class="container"> -->
    <div id="spreadsheet" style="box-shadow: 0 0 50px 10px rgb(0 0 0 / 10%);margin-left: 50%;transform: translateX(-50%);"></div>
<!-- </div> -->



<!-- 单行数据点 -->
<script type="text/html" template lay-done="layui.data.checkData(d.params)">
</script>

<style>
    .hide {
        display: none;
    }
</style>

<script>
    layui.use(['admin', 'laytpl', 'form', 'laypage', 'layer', 'view',
        'setter', 'upload','laydate'
    ], function () {
        var $ = layui.$,
            admin = layui.admin,
            table = layui.table,
            laytpl = layui.laytpl,
            form = layui.form,
            laydate = layui.laydate
            laypage = layui.laypage,
            layer = layui.layer,
            view = layui.view,
            setter = layui.setter,
            tipsIndex = null;
            var nowTime = ""
            treeData = null;
            form.render()
       
            $(function(){
                var now = new Date();
                var year = now.getFullYear(); //得到年份
                var month = now.getMonth();//得到月份
                var date = now.getDate();//得到日期
                month = month + 1;
                if (month < 10) month = "0" + month;
                if (date < 10) date = "0" + date;
                nowTime = year + "-" + month + "-" + date;
                
            });


            save = function(){
                table.download()
            }

            laydate.render({
                elem:"#year",
                type:'year',
                value:new Date()
            })

            form.on('select(dateSelect)',function(event){
                if(event.value === 'month'){
                    laydate.render({
                        elem:"#month",
                        type:'month',
                        value:new Date()
                    })
                    laydate.render({
                        elem:"#month2",
                        type:'month',
                        value:new Date()
                    })
                    $('#month').removeClass('hide').siblings().addClass('hide')
                    $('#month2').removeClass('hide')
                }else if(event.value === 'day'){
                    laydate.render({
                        elem:"#day",
                        value:new Date()
                    })
                    laydate.render({
                        elem:"#day2",
                        value:new Date()
                    })
                    $('#day').removeClass('hide').siblings().addClass('hide')
                    $('#day2').removeClass('hide');
                }else{
                    laydate.render({
                        elem:'#year',
                        type:'year',
                        value:new Date()
                    })
                    $('#year').removeClass('hide').siblings().addClass('hide')
                }
                
            })


        layui.data.checkData = function () {
            var data = layui.data('customItem-data').data
            $('.luomi-title').text(data.name + '查看' + "   id:" + data.id)

            layui.data('table',{
                key:'id',
                value:data.id
            })

            // 树形结构

            var excel = function(DayMonthYear,intime,outime){
                            // 自定义报表初始化
            admin.req({
                method: 'get',
                url: 'http://www.iotddc.com/IOTDDC/customreport/getCustomreportView',
                data: {
                    token: 'EEAADD2299AAEE226677331177885599',
                    id: data.id,
                    DayMonthYear: DayMonthYear,
                    intime: intime,
                    outime: outime,
                    intimeday: nowTime,
                    outimeday: nowTime,
                    ExportExcel: '0'
                },
                done: function (res) {
                    // console.log(res);
                    var col = res.columnnumber ? res.columnnumber : 20
                    var row = res.rownumber ? res.rownumber : 24

                    // console.log(res.style);
                    // console.log(eval('[' + res.style + ']'));


                    var selectionActive = function (instance, x1, y1, x2, y2, origin) {
                        var cellName1 = jexcel.getColumnNameFromId([x1, y1]);
                        var cellName2 = jexcel.getColumnNameFromId([x2, y2]);
                        layui.data('table',{
                            key:'data',
                            value:{
                                cellName1:cellName1,
                                col1:x1,
                                row1:y1,
                                col2:x2,
                                row2:y2
                            }
                        })

                        x3 = x1;
                        y3 = y1;
                        x4 = x2;
                        y4 = y2;
                        console.log('选中了 ' + cellName1 + ' 至 ' +
                            cellName2 + '');
                        console.log('选中了' + x1, y1 + '至', x2, y2);
                    }

                    merge = function(){
                        var data = layui.data('table').data
                        // console.log(data.cellName1,data.col2-data.col1+1,data.row2-data.row1+1);
                        table.setMerge(data.cellName1,data.col2-data.col1+1,data.row2-data.row1+1)
                    }


             

                    table = jspreadsheet(document.getElementById('spreadsheet'), {
                        data: [],
                        minDimensions: [col, row],
                        tableOverflow: true,
                        tableWidth: "1055px",
                        tableHeight: "auto",

                        // 选择事件
                        onselection: selectionActive,

                    })
                    // 设置列宽
                    if (res.columnnumber) {
                        var width = res.width.substring(1, res.width.length - 1).split(',')
                        layui.each(width, function (index, item) {
                            if (item !== 'null') {
                                table.setWidth(index, item)
                            }

                        })

                        // 设置行高
                        var height = res.height.substring(1, res.height.length - 1).split(',')
                        layui.each(height, function (index, item) {
                            if (item !== 'null') {
                                table.setHeight(index, item)
                            }
                        })

                        // 合并单元格
                        var merge = res.merge.substring(1, res.merge.length - 1).split(',')
                        if (merge[0] !== "}") {
                            layui.each(merge, function (index, item) {
                                item = item.split('|')
                                table.setMerge(jexcel.getColumnNameFromId([item[2],
                                        item[3]
                                    ]),
                                    item[0] - '0', item[1] - '0');
                            })
                        }

                        // 更新单元格取值
                        if(res.value != ''){
                        var value = res.value.split(',')
                        layui.each(value, function (index, item) {
                            let item_cell = item.split('|')
                            var item_cell_content = ''
                            if (item_cell.length > 3) {
                                for (let i = 0; i <= item_cell_length - 3; i++) {
                                    item_cell_content += item_cell[i]
                                }
                            } else {
                                item_cell_content = item_cell[0]
                            }
                            item_cell_row = item_cell[item_cell.length - 1];
                            item_cell_col = item_cell[item_cell.length - 2];


                            table.setValueFromCoords(item_cell_col, item_cell_row,
                                item_cell_content)
                        })
                    }

                   
                    }

                    // console.log(table.getStyle());

                    // // 设置表格样式
                    var styleMap=new Map();
                    if (res.style!=null && res.style!=""){
					    var style=res.style.replace("{", "")
				        style=style.replace("}","")
                        // console.log(style);
					    var style=style.split("，")
                        // console.log(style);
					for(var i=0;i<style.length;i++){
					  var str=style[i].split("|")
                    //   console.log(str);
					  cellName = jexcel.getColumnNameFromId([str[1], str[2]]);
					//   console.log(cellName+" "+str[1]+str[2]+str[0])
					  var stylepm=str[0].split(";")
                    //   console.log(stylepm);
					  for(var j=0;j<stylepm.length-1;j++){
					    var kv=stylepm[j].split(":")
                        // table.setStyle(cellName,kv[0].trim(),kv[1].trim())
					    if (kv.length>0 && kv[0]!=null && kv[1]!=null && kv[0]!="" && kv[1]!=""){
					    		//console.log(cellName+"=("+kv[0].trim()+")"+":("+kv[1].trim()+")")
					    	if (kv[0].trim()=="border-top"){
					    		table.setStyle(cellName,'border-top','1px solid #000')
					    	}else if (kv[0].trim()=="border-left"){
					    		table.setStyle(cellName,'border-left','1px solid #000')
					    	}else if (kv[0].trim()=="border-right"){
					    		table.setStyle(cellName,'border-right','1px solid #000')
					    	}else if (kv[0].trim()=="border-bottom"){
					    		table.setStyle(cellName,'border-bottom','1px solid #000')
					    	}else if (kv[0].trim()=="border-width"){
					    		//console.log("kv[0].trim()=="+kv[0].trim())
					    		table.setStyle(cellName,'border-top','1px solid #000')
					    		table.setStyle(cellName,'border-left','1px solid #000')
					    		table.setStyle(cellName,'border-right','1px solid #000')
					    		table.setStyle(cellName,'border-bottom','1px solid #000')
					    	}else if (kv[0].trim()=="background-color" || kv[0].trim()=="color" || (kv[0].trim()=='text-align' && kv[1].trim()!='center')|| kv[0].trim()=='font-weight' || kv[0].trim()=='font-size' ){  //颜色
                                // console.log(cellName,kv);  // 当前要加样式的单元格编号 要加的样式:[什么样式,值]
					    		var flag=0;
                                // console.log(res.merge);  
					    		if (res.merge!=null && res.merge!="" && res.merge!=undefined){
                                    // console.log(merge);  // [合并列数,合并行数,列号,行号]
                                    // console.log(str[1],str[2]); // 当前要改变样式的 行号,列号
						    		for(var x=0;x<merge.length;x++){
	//					    			console.log("merge1.length="+merge1.length)
						    			var str1=merge[x].split("|")
                                        // console.log(str1); 
                                        // console.log(str[1],str1[2]);
	//					    			console.log("merge1.length="+str[1]+">="+str1[2]+" "+str[1]+"<="+(parseInt(str1[2])+parseInt(str1[0])-1)+" "+ 
	//					    				   str[2]+">="+str1[3]+" "+ str[2]+"<="+(parseInt(str1[3])+parseInt(str1[1])-1))
						    			if (parseInt(str[1])>=parseInt(str1[2]) && parseInt(str[1])<=(parseInt(str1[2])+parseInt(str1[0])-1) && 
						    				   parseInt(str[2])>=parseInt(str1[3]) && parseInt(str[2])<=(parseInt(str1[3])+parseInt(str1[1])-1)){
						    			  flag=1;
						    			  cellName1 = jexcel.getColumnNameFromId([str1[2], str1[3]]);
                                        //   console.log(cellName1); // 要合并的整号
						    			  //console.log(cellName1+"--"+jexcel.getColumnNameFromId([(parseInt(str1[2])+parseInt(str1[0])-1), (parseInt(str1[3])+parseInt(str1[1])-1)])+":"+kv[0].trim()+" "+kv[1].trim())
						    			  //console.log(kv[0].trim()=="color")
						    			  //console.log(styleMap[cellName1+'color']==undefined)
						    			  //console.log(kv[1].trim()!="rgb(0, 0, 0)")
						    			  if (kv[0].trim()=="color" && styleMap[cellName1+'color']==undefined && kv[1].trim()!="rgb(0, 0, 0)"){
						    			  	//console.log("SETCOLOR--"+cellName1+":"+kv[0].trim()+" "+kv[1].trim())
							    			  styleMap[cellName1+'color']=1
							    			  table.setStyle(cellName1,kv[0].trim(),kv[1].trim())
							    			  //break;
						    			  }
                                          if (kv[0].trim()=="text-align" && styleMap[cellName1+'text-align']==undefined){
						    			  	//console.log("SETCOLOR--"+cellName1+":"+kv[0].trim()+" "+kv[1].trim())
							    			  styleMap[cellName1+'text-align']=1
							    			  table.setStyle(cellName1,kv[0].trim(),kv[1].trim())
							    			  //break;
						    			  }
                                          if (kv[0].trim()=="font-weight" && styleMap[cellName1+'font-weight']==undefined){
						    			  	//console.log("SETCOLOR--"+cellName1+":"+kv[0].trim()+" "+kv[1].trim())
							    			  styleMap[cellName1+'font-weight']=1
							    			  table.setStyle(cellName1,kv[0].trim(),kv[1].trim())
							    			  //break;
						    			  }
                                          if (kv[0].trim()=="font-size" && styleMap[cellName1+'font-size']==undefined){
						    			  	//console.log("SETCOLOR--"+cellName1+":"+kv[0].trim()+" "+kv[1].trim())
							    			  styleMap[cellName1+'font-size']=1
							    			  table.setStyle(cellName1,kv[0].trim(),kv[1].trim())
							    			  //break;
						    			  }
						    			  if (kv[0].trim()=="background-color" && styleMap[cellName1]==undefined && kv[1].trim()!="rgb(0, 0, 0)"){
						    			  	//console.log("SETCOLOR--"+cellName1+":"+kv[0].trim()+" "+kv[1].trim())
							    			  styleMap[cellName1]=1
							    			  table.setStyle(cellName1,kv[0].trim(),kv[1].trim())
							    			  //break;
						    			  }
                                          
						    			}
							      }
                                //   console.log('----');
						    		if (flag==0){
						    			//console.log(cellName+":"+kv[0].trim()+" "+kv[1].trim())
						    			table.setStyle(cellName,kv[0].trim(),kv[1].trim())
						    		}
								  }else{
                                    table.setStyle(cellName,kv[0].trim(),kv[1].trim())
								  }
					    	}else if (kv[0].trim()!="border-style" && kv[0].trim()!="border-color" && kv[0].trim()+kv[1].trim()!="text-aligncenter"){
					  			table.setStyle(cellName,kv[0].trim(),kv[1].trim())
					  		}
					  	}
					 }
					}
				}


                
                }
            });






            }


            excel('day',nowTime,nowTime);



            form.on('submit(custom-check-btn)',function(obj){
                var value = obj.field;
                var intime = "";
                var outime = "";
                var flag = 0;
                var DayMonthYear = value.date
                if(DayMonthYear === 'year'){
                    if(value.year === ""){
                        layer.msg('请选择时段')
                        flag = 1;
                    }else{
                        intime = value.year;
                        outime = value.year
                    }
                }else if(DayMonthYear === 'month'){
                    if(value.month === "" || value.month2 === ""){
                        layer.msg('请选择时段')
                        flag = 1
                    }else{
                        intime = value.month;
                        outime = value.month2;
                    }
                }else if(DayMonthYear === 'day'){
                    if(value.day === "" || value.day2 === ""){
                        layer.msg('请选择时段')
                        flag = 1
                    }else{
                        intime = value.day;
                        outime = value.day2
                    }
                }
                if(flag === 0){
                    excel(DayMonthYear,intime,outime);
                }

            })




        }




    });
</script>